#include "serial.h"
#include "define.h"

#include "QtWebSockets/QWebSocketServer"
#include "QtWebSockets/QWebSocket"
#include <QSettings>
//#include <QDebug>
serial::serial(QSerialPort *serialPort, QObject *parent)
    : QObject(parent),
      m_serialPort(serialPort),
      m_pWebSocketServer(Q_NULLPTR),
      m_clients(),
      port(1234)

{
    m_rev_soc = new QUdpSocket(this);
    m_rev_soc->bind(REV_PORT, QUdpSocket::ShareAddress);
    connect(m_rev_soc, SIGNAL(readyRead()), SLOT(handleSocReadyRead()));


    m_control_soc = new QUdpSocket(this);
    m_control_soc->bind(CMD_PORT);
    connect(m_control_soc, SIGNAL(readyRead()), SLOT(handleCmdReadyRead()));

    m_send_soc = new QUdpSocket(this);

    connect(m_serialPort, SIGNAL(readyRead()), SLOT(handleSerialReadyRead()));
    connect(m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)), SLOT(handleError(QSerialPort::SerialPortError)));

    m_pWebSocketServer = new QWebSocketServer(QStringLiteral(""),
                                              QWebSocketServer::NonSecureMode,
                                              this);
    if (m_pWebSocketServer->listen(QHostAddress::Any, port))
    {
        qDebug() << "Chat Server listening on port" << port;
        connect(m_pWebSocketServer, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
    }

    QSettings set("auxun", "control");
    QString number = set.value("number").toString();
    brocast_byte.append(number);

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(heartbeat()));
    timer->start(1000);
}

serial::~serial()
{
}

void serial::handleSocReadyRead()
{
  qDebug() << "handleSocReadyRead";
    while (m_rev_soc->hasPendingDatagrams()) {
        QByteArray datagram;
        //m_rev_soc->;
        //QHostAddress addr;
        datagram.resize(m_rev_soc->pendingDatagramSize());
        m_rev_soc->readDatagram(datagram.data(), datagram.size());
        //qDebug() << "addr = " << addr.toString();
        QSettings set("auxun", "control");
        QString number = set.value("number").toString();

        QByteArray send_data;
        QList<QByteArray> list = datagram.split(QString(",").data()->toLatin1());
        for (int i = 0; i < list.size(); ++i) {
            send_data.push_back(list.at(i).toInt());
            //if (list.at(i) )
            //    cout << "Found Jane at position " << i << endl;
        }
        //qDebug() << send_data;

        //qDebug() <<datagram;
        //if (QString(datagram.at(0)) == number)
            //m_serialPort->write(datagram.mid(1));//发送时去掉编号
          m_serialPort->write(send_data);//发送时去掉编号
    }
}
/*
数据头加上机器人编号.
*/
void serial::handleSerialReadyRead()
{
    QByteArray serial_data = m_serialPort->readAll();
    QSettings set("auxun", "control");
    QString number = set.value("number").toString();
    qDebug() << "serial_data = " << serial_data;
    QByteArray send_data = number.toInt() + serial_data;
    qDebug() << send_data.toHex();
    //m_send_soc->writeDatagram(send_data, QHostAddress::Broadcast, SENDER_PORT);
    Q_FOREACH (QWebSocket *pClient, m_clients)
    {
        pClient->sendTextMessage(QString(send_data.toHex()));
    }
}

void serial::handleCmdReadyRead()
{
    while (m_control_soc->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(m_control_soc->pendingDatagramSize());
        m_control_soc->readDatagram(datagram.data(), datagram.size());
        QSettings set("auxun", "control");
        QString number = set.value("number").toString();
        if (QString(datagram.at(0)) == number)
            handleCmd(datagram.mid(1));
    }
}

void serial::handleCmd(const QByteArray &cmds)
{
    if (cmds.size() > 0) {
        switch (cmds.at(0)){
            case SET_NUM: {
                QSettings set("auxun", "control");
                set.setValue("number", cmds.at(1));
                break;
            }
            case SET_PATH: {
                QSettings path("auxun", "path");
                path.setValue(("path/" + cmds.at(1)), cmds.mid(2));
                refreshPath(cmds);
                break;
                //path.setValue("", );
            }
            default:
                break;
        }
    }
}
//这里还需要修改数据格式......
void serial::refreshPath(const QByteArray &path)
{
    m_serialPort->write(path);
}

void serial::handleError(QSerialPort::SerialPortError serialPortError)
{
    Q_UNUSED(serialPortError);
}

//! [onNewConnection]
void serial::onNewConnection()
{
    QWebSocket *pSocket = m_pWebSocketServer->nextPendingConnection();
    qDebug() << "onNewConnection";
    connect(pSocket, SIGNAL(textMessageReceived(QString)), this, SLOT(processMessage(QString)));
    connect(pSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));

    m_clients << pSocket;
}

//! [processMessage]
void serial::processMessage(const QString & message)
{
    qDebug() << "processMessage = " << message;
    QStringList list = message.split(',');
    QByteArray send_data;
    for (int i = 0; i < list.size(); i++)
        send_data.append(QString(list.at(i)).toInt());
        //cout << fonts.at(i).toLocal8Bit().constData() << endl;
    QWebSocket *pSender = qobject_cast<QWebSocket *>(sender());
    Q_FOREACH (QWebSocket *pClient, m_clients)
    {
        if (pClient != pSender) //don't echo message back to sender
        {

            m_serialPort->write(send_data);//发送时去掉编号
            //pClient->sendTextMessage(message);
        }
    }
}
//! [processMessage]

//! [socketDisconnected]
void serial::socketDisconnected()
{
    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
    if (pClient)
    {
        m_clients.removeAll(pClient);
        pClient->deleteLater();
    }
}

void serial::heartbeat()
{
  //qDebug() << brocast_byte << brocast_byte.toInt();
  m_send_soc->writeDatagram(brocast_byte, QHostAddress::Broadcast, SENDER_PORT);
}
